<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="es6,TypeScript,js," />





  <link rel="alternate" href="/atom.xml" title="二羊的小窝仔" type="application/atom+xml" />






<meta name="description" content="ES 新特性 ECMAScript 是 JavaScript 的扩展语言  JavaScript &#x3D; ECMAScript + webapi(BOM,DOM)  ES2015 称之为 ES6  不是程序中的方法，而是数学中的函数">
<meta property="og:type" content="article">
<meta property="og:title" content="ES 新特性与 TypeScript、JS 性能优化">
<meta property="og:url" content="https://eryangboy.github.io/notes/notes/typescript/index.html">
<meta property="og:site_name" content="二羊的小窝仔">
<meta property="og:description" content="ES 新特性 ECMAScript 是 JavaScript 的扩展语言  JavaScript &#x3D; ECMAScript + webapi(BOM,DOM)  ES2015 称之为 ES6  不是程序中的方法，而是数学中的函数">
<meta property="og:locale">
<meta property="article:published_time" content="2020-12-12T08:34:41.000Z">
<meta property="article:modified_time" content="2020-12-12T09:17:17.762Z">
<meta property="article:author" content="二羊">
<meta property="article:tag" content="es6">
<meta property="article:tag" content="TypeScript">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://eryangboy.github.io/notes/notes/typescript/"/>





  <title>ES 新特性与 TypeScript、JS 性能优化 | 二羊的小窝仔</title>
  








  <script type="text/javascript" src="/js/src/clicklove.js"></script>
<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title" >
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="with-love" id="animate" style='position: relative;
    left: -4px;
    top: 7px;'> 
          <i class="fa fa-heart"></i>
        </span>
        <span class="site-title">二羊的小窝仔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">无需凭借谁的光，我就是自己的太阳</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            笔记
          </a>
        </li>
      
        
        <li class="menu-item menu-item-life">
          <a href="/categories/life/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            生活
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://eryangboy.github.io/notes/notes/typescript/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/favicon.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="二羊的小窝仔">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ES 新特性与 TypeScript、JS 性能优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-12T16:34:41+08:00">
                2020-12-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/notes/" itemprop="url" rel="index">
                    <span itemprop="name">notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_value_page_pv"></span>次阅读


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="ES-新特性"><a href="#ES-新特性" class="headerlink" title="ES 新特性"></a>ES 新特性</h1><ul>
<li><p>ECMAScript 是 JavaScript 的扩展语言</p>
</li>
<li><p>JavaScript = ECMAScript + webapi(BOM,DOM)</p>
</li>
<li><p>ES2015 称之为 ES6</p>
</li>
<li><p>不是程序中的方法，而是数学中的函数</p>
</li>
<li><a id="more"></a>
</li>
<li><p>解决原有语法上的一些问题或者不足</p>
</li>
<li><p>对原有语法进行加强</p>
</li>
<li><p>全新的对象，全新的方法，全新的功能</p>
</li>
<li><p>全新的数据类型和数据结构</p>
</li>
</ul>
<ol>
<li><p>let 与块级作用域<br> 作用域：全局作用域，函数作用域，块级作用域</p>
<p> let 是块级作用域<br> 不会变量提升<br> 暂时性死区<br> 不允许重复声明</p>
</li>
<li><p> const：常量 声明过后不可以再修改</p>
</li>
<li><p>数组的解构<br> let arr = [1, 2, 3]<br> const [a,b,c] = arr</p>
</li>
<li><p> 对象的结构</p>
</li>
</ol>
<p>const obj = { name: “zhangsan”, age: 22 };<br>const { name} = obj;</p>
<p>默认值 const obj = { age: 22 };<br>const { name: _name = “lise” } = obj;</p>
<ol start="5">
<li><p>模版字符串<br>const name = ‘zhangsan’<br>const str = <code>hello $&#123;name&#125;</code></p>
</li>
<li><p>带标签的模板字符串</p>
</li>
</ol>
<p>// 模板字符串的标签就是一个特殊的函数，可以用来实现模板引擎<br>// 使用这个标签就是调用这个函数<br>// const str = console.log<code>hello world</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> name = <span class="string">&#x27;tom&#x27;</span></span><br><span class="line"><span class="keyword">const</span> gender = <span class="literal">false</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">myTagFunc</span> (<span class="params">strings, name, gender</span>) </span>&#123;</span><br><span class="line"><span class="comment">// console.log(strings, name, gender)</span></span><br><span class="line"><span class="comment">// return &#x27;123&#x27;</span></span><br><span class="line"><span class="keyword">const</span> sex = gender ? <span class="string">&#x27;man&#x27;</span> : <span class="string">&#x27;woman&#x27;</span></span><br><span class="line"><span class="keyword">return</span> strings[<span class="number">0</span>] + name + strings[<span class="number">1</span>] + sex + strings[<span class="number">2</span>]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> result = myTagFunc<span class="string">`hey, <span class="subst">$&#123;name&#125;</span> is a <span class="subst">$&#123;gender&#125;</span>.`</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(result)</span><br></pre></td></tr></table></figure>

<ol start="7">
<li><p>对象字面量，方括号里面的执行结果作为对象属性名</p>
<figure class="highlight autoit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> obj = &#123;</span><br><span class="line">    foo: <span class="number">123</span>,</span><br><span class="line">    [Math.<span class="built_in">random</span>]: <span class="string">&#x27;hh&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>Object.assign 可传入任意参数，第一个为目标对象，返回值就是目标对象，三等号为 true</p>
</li>
<li><p>Object.is 可以比较 NaN，Object.is(NaN,NaN)为 true</p>
</li>
<li><p>proxy 可以通过 set get 方法监听对象属性赋值和读取</p>
</li>
</ol>
<blockquote>
<p>与 definedProperty 对比：definedProperty 只能监听读写，但是 proxy 可以监听多种操作</p>
</blockquote>
<blockquote>
<p>proxy 还可以监视数组</p>
</blockquote>
<ol start="11">
<li><p>Reflect 统一对象的操作方式</p>
</li>
<li><p>静态方法中的 this 指向当前类型</p>
</li>
<li><p>set 可以链式调用 s.add().add().add()。数组展开符后可以直接跟一个 set 对象</p>
</li>
</ol>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[... new Set([<span class="number">1</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">3</span>])]</span><br></pre></td></tr></table></figure>

<ol start="14">
<li><p>map 和对象类似，对象的键值只能是字符串和 Symbol，map 的键值可以是任意类型。set 方法存，get 方法取</p>
</li>
<li><p>Symbol 可以用来模拟对象的私有成员。为对象添加一个独一无二的属性，因为每次新建 Symbol 都不一样。<br>Symbol.for(‘’)只要传入的字符串相等，生成的 Symbol 对象就一样<br><code>Symbol.for(&#39;1&#39;) === Symbol.for(1) // true const obj = &#123; [Symbol.toStringTag]: &#39;XObject&#39;, [Symbol]: &#39;Symbol value&#39; &#125; obj.toString() // [object XObject] Object.getOwnPropertySymbols(obj) // 这样才能获取到Symbol类型的属性，Object.keys只能获取字符串类型的属性名</code></p>
</li>
<li><p>for of 循环可以使用 break 终止循环。forEach 不行。可以循环 Set，Map。遍历 map 会返回数组，含有 key 和 value。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 遍历对象，实现可迭代模式</span></span><br><span class="line"><span class="keyword">const</span> obj = &#123;</span><br><span class="line">    store: [<span class="string">&#x27;foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz&#x27;</span>],</span><br><span class="line">    [<span class="built_in">Symbol</span>.iterator]: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span></span><br><span class="line">        <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            next: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">                <span class="keyword">const</span> result = &#123;</span><br><span class="line">                    value: self.store[index],</span><br><span class="line">                    done: index &gt;= self.store.length</span><br><span class="line">                &#125;</span><br><span class="line">                index++</span><br><span class="line">                <span class="keyword">return</span> result</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> item <span class="keyword">of</span> obj) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(item)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>迭代器用途：对外提供统一遍历接口</p>
</li>
<li><p>生成器对象也实现了 iterator 接口。应用：发号器，不断自增一不用担心死循环</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 用生成器函数实现iterator方法</span></span><br><span class="line">[<span class="built_in">Symbol</span>.iterator]: <span class="function"><span class="keyword">function</span> * (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> all = [...this.store]</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> item <span class="keyword">of</span> all) &#123;</span><br><span class="line">        <span class="keyword">yield</span> item</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="ES2016"><a href="#ES2016" class="headerlink" title="ES2016"></a>ES2016</h2><ul>
<li>新增数组 includes 方法，可以判断是否有 NaN，indexOf 却不行</li>
</ul>
<figure class="highlight arcade"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = [<span class="number">1</span>,<span class="number">2</span>,<span class="literal">NaN</span>]</span><br><span class="line">a.indexOf(<span class="literal">NaN</span>)</span><br><span class="line"><span class="comment">// 输出-1</span></span><br><span class="line">a.includes(<span class="literal">NaN</span>)</span><br><span class="line"><span class="comment">// 输出true</span></span><br></pre></td></tr></table></figure>

<ul>
<li>新增指数运算符 **</li>
</ul>
<h2 id="ES2017"><a href="#ES2017" class="headerlink" title="ES2017"></a>ES2017</h2><ul>
<li><p>Object.values<br>返回对象中所有值</p>
</li>
<li><p>Object.entries<br>数组形式返回对象所有键值对。可以直接 for of 循环；可以将一个对象转换成 map 类型</p>
</li>
<li><p>Object.getOwnPropertyDescriptor<br>用 Object.assign 复制的时候可以获取完整描述，配合 get set 方法使用</p>
</li>
</ul>
<h1 id="TypeScript-语言"><a href="#TypeScript-语言" class="headerlink" title="TypeScript 语言"></a>TypeScript 语言</h1><ol>
<li><p>强类型和弱类型（类型安全）<br>强类型：形参和实参类型必须相同，不允许有任意的隐式类型转换<br>弱类型：不会限制实参的类型，允许有任意的隐式类型转换</p>
</li>
<li><p>静态类型和动态类型（类型检查）<br>静态类型：一个变量在声明时，类型就是明确的，声明过后，不可以再修改<br>动态类型：运行阶段，才可以明确变量的类型，声明过后，还可以修改</p>
<p>js 是弱类型和动态类型，缺乏了类型系统的可靠性</p>
</li>
<li><p>弱类型的问题</p>
<ol>
<li>类型异常只能等到运行时发现</li>
<li>类型不明确造成函数功能发生改变</li>
<li>类型不明确造成对象属性值的错误用法</li>
</ol>
<p>强类型的优势</p>
<ul>
<li>错误提早暴露</li>
<li>代码更智能，编码更准确</li>
<li>重构更牢靠</li>
<li>减少不必要的类型判断</li>
</ul>
</li>
<li><p>Flow js 的类型检查器</p>
</li>
</ol>
<h3 id="静态类型和动态类型（类型检查角度）"><a href="#静态类型和动态类型（类型检查角度）" class="headerlink" title="静态类型和动态类型（类型检查角度）"></a>静态类型和动态类型（类型检查角度）</h3><h3 id="Flow，JavaScript-类型检查器（2014，Facebook）"><a href="#Flow，JavaScript-类型检查器（2014，Facebook）" class="headerlink" title="Flow，JavaScript 类型检查器（2014，Facebook）"></a>Flow，JavaScript 类型检查器（2014，Facebook）</h3><p>通过类型注解来控制类型，类型不符合保存后 Flow 语法就可以检测出来异常</p>
<figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title">sum</span> (a:number,b) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="type">a</span> + b</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>flow 类型推断：根据代码中使用情况推断出类型</p>
<p>类型注解示例：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> num: <span class="built_in">number</span> = <span class="number">100</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">s</span> (<span class="params">a:<span class="built_in">string</span></span>):<span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + <span class="string">&#x27;s&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> a: <span class="built_in">string</span> = <span class="string">&#x27;sdf&#x27;</span></span><br><span class="line"><span class="keyword">const</span> b: <span class="built_in">number</span> = <span class="literal">NaN</span></span><br><span class="line"><span class="keyword">const</span> c: <span class="built_in">boolean</span> = <span class="literal">false</span></span><br><span class="line"><span class="keyword">const</span> d: <span class="literal">null</span> = <span class="literal">null</span></span><br><span class="line"><span class="keyword">const</span> e: <span class="built_in">void</span> = <span class="literal">undefined</span></span><br><span class="line"><span class="keyword">const</span> f: symbol = <span class="built_in">Symbol</span>()</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> arr1: Arry&lt;<span class="built_in">number</span>&gt; = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="keyword">const</span> arr2: <span class="built_in">number</span>[] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="comment">// 元祖</span></span><br><span class="line"><span class="keyword">const</span> foo: [<span class="built_in">string</span>, <span class="built_in">number</span>] = [<span class="string">&#x27;foo&#x27;</span>, <span class="number">100</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象类型</span></span><br><span class="line"><span class="comment">// 指定属性名</span></span><br><span class="line"><span class="keyword">const</span> obj:&#123;foo?: <span class="built_in">string</span>, <span class="attr">bar</span>: <span class="built_in">number</span>&#125; = &#123;<span class="attr">bar</span>: <span class="number">100</span>&#125;</span><br><span class="line"><span class="comment">// 不指定属性名，只指定类型</span></span><br><span class="line"><span class="keyword">const</span> obj1: &#123;[<span class="built_in">string</span>]: <span class="built_in">string</span>&#125; = &#123;&#125;</span><br><span class="line">obj1.key = <span class="string">&#x27;value&#x27;</span></span><br><span class="line">obj1.key1 = <span class="number">100</span> <span class="comment">// 错误，上面规定是字符串类型</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 函数类型</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span> (<span class="params">callback: (<span class="built_in">string</span>, <span class="built_in">number</span>) =&gt; <span class="built_in">void</span></span>) </span>&#123;</span><br><span class="line">    callback(<span class="string">&#x27;string&#x27;</span>, <span class="number">100</span>)</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="function"><span class="keyword">function</span> (<span class="params">str, n</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// str =&gt; string</span></span><br><span class="line">    <span class="comment">// n =&gt; number</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 特殊类型</span></span><br><span class="line"><span class="keyword">const</span> a: <span class="string">&#x27;foo&#x27;</span> = <span class="string">&#x27;foo&#x27;</span> <span class="comment">// 字面量只能是&#x27;foo&#x27;</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">type</span>: <span class="string">&#x27;success&#x27;</span> | <span class="string">&#x27;warning&#x27;</span> | <span class="string">&#x27;danger&#x27;</span> = <span class="string">&#x27;success&#x27;</span> <span class="comment">// 联合类型，只能是这几种</span></span><br><span class="line"><span class="keyword">const</span> b: <span class="built_in">string</span> | <span class="built_in">number</span> = <span class="string">&#x27;s&#x27;</span> <span class="comment">// 联合类型，只能是字符串或者数字</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> StringOrNumber = <span class="built_in">string</span> | <span class="built_in">number</span> <span class="comment">// 可以定义类型的别名</span></span><br><span class="line"><span class="keyword">const</span> c: StringOrNumber = <span class="number">100</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> gender: ?<span class="built_in">number</span> = <span class="literal">null</span> <span class="comment">// 表示可以接受number或者null或者undefined</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// mixed、any</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">passMixed</span> (<span class="params">value: mixed</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span>(value) === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">        <span class="comment">// xxx</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">passMixed(<span class="string">&#x27;sf&#x27;</span>)</span><br><span class="line">passMixed(<span class="number">100</span>) <span class="comment">// mixed相当于所有类型的联合类型</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">passAny</span> (<span class="params">value: <span class="built_in">any</span></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 同样接受任意类型参数，any是弱类型，mixed是强类型（mixed一旦确定类型后就不可修改）</span></span><br></pre></td></tr></table></figure>

<h3 id="TypeScript"><a href="#TypeScript" class="headerlink" title="TypeScript"></a>TypeScript</h3><ol>
<li><p>非严格模式下，允许 string，number，Boolean，void；类型的值为 null</p>
</li>
<li><p>ts 默认所有文件都处在一个全局作用域中，不同文件可以相互访问变量，所以很容易变量名冲突，解决方法就是使用模块式，变成模块作用域</p>
</li>
<li><p>对象 object 类型可以接受函数，对象，数组。如果想只接受对象，需要用对象字面量形式{foo:number,bar:string}</p>
</li>
<li><p>数组类型</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr:number[] = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span> <span class="params">(<span class="rest_arg">...args</span>: number[])</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> args.reduce((prev, current) =&gt; prev + current, <span class="number">0</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>元组类型：固定长度固定类型的数组</p>
<figure class="highlight autoit"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> tuple: [<span class="built_in">number</span>, <span class="built_in">string</span>] = [<span class="number">18</span>, <span class="string">&#x27;zec&#x27;</span>]</span><br></pre></td></tr></table></figure></li>
<li><p>枚举类型：用对象模拟</p>
<figure class="highlight crystal"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">enum</span> <span class="title">status</span> &#123;</span></span><br><span class="line">    draft = <span class="number">0</span>,</span><br><span class="line">    published = <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">/<span class="regexp">/ ts中enum关键字表示枚举类型</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 不指定值会默认从0开始累加</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 可以是数字或者字符串类型</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 枚举类型编译后会生成一个双向键值对对象</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">const enum status &#123;</span></span><br><span class="line"><span class="regexp">    draft,</span></span><br><span class="line"><span class="regexp">    published</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 常量枚举，编译后会移除</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数类型</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sun</span><span class="params">(a:number,b:number)</span>: string </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 参数个数和类型都固定，如果想要参数个数不确定可以使用es6的默认参数或者剩余参数...表达式</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>隐式类型推断</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let age = <span class="number">18</span> <span class="regexp">//</span> 隐式推断为number，之后再赋值其他类型会报错</span><br><span class="line">let foo; <span class="regexp">//</span> 声明变量没有赋值，则推断为any类型</span><br></pre></td></tr></table></figure></li>
<li><p>类型断言：明确告诉 ts 变量的类型</p>
<figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const nums = [<span class="number">110</span>, <span class="number">120</span>, <span class="number">119</span>, <span class="number">112</span>]</span><br><span class="line">const <span class="keyword">res</span> = nums.<span class="keyword">find</span>(i =&gt; i &gt; <span class="number">0</span>) // <span class="keyword">ts</span>推断<span class="keyword">res</span>类型为<span class="keyword">number</span>或者undefined</span><br><span class="line">const num1 = <span class="keyword">res</span> <span class="keyword">as</span> <span class="keyword">number</span> // 明确<span class="keyword">res</span>是一个<span class="keyword">number</span>类型</span><br><span class="line">const num2 = <span class="symbol">&lt;number&gt;</span><span class="keyword">res</span> // 这种方式与JSX语法冲突</span><br></pre></td></tr></table></figure></li>
<li><p>接口：用来约束对象的结构，对象实现一个接口，必须拥有这个接口定义的成员。编译后没有</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Post &#123;</span><br><span class="line">    title: <span class="built_in">string</span></span><br><span class="line">    content: <span class="built_in">string</span></span><br><span class="line">    subtitle?: <span class="built_in">string</span> <span class="comment">// 可选成员</span></span><br><span class="line">    <span class="keyword">readonly</span> summary: <span class="built_in">string</span> <span class="comment">// 只读成员</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printPost</span> (<span class="params">post: Post</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(post.title)</span><br><span class="line">    <span class="built_in">console</span>.log(post.content)</span><br><span class="line">    post.summary = <span class="string">&#x27;123&#x27;</span> <span class="comment">// 报错，不允许修改</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 显示要求传入的post参数必须要有title，content</span></span><br><span class="line">printPost(&#123;</span><br><span class="line">    title: <span class="string">&#x27;&#x27;</span>,</span><br><span class="line">    content: <span class="string">&#x27;&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 动态成员</span></span><br><span class="line"><span class="keyword">interface</span> Cachee &#123;</span><br><span class="line">    [key: <span class="built_in">string</span>]: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> cache: Cachee = &#123;&#125;</span><br><span class="line">cache[<span class="string">&#x27;name&#x27;</span>] = <span class="string">&#x27;name&#x27;</span></span><br><span class="line"><span class="comment">// 接口约束方法</span></span><br><span class="line"><span class="keyword">interface</span> Eat &#123;</span><br><span class="line">    eat (food: <span class="built_in">string</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> Run &#123;</span><br><span class="line">    run (distance: <span class="built_in">number</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 实现接口的类必须有接口中定义的方法</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="title">implements</span> <span class="title">Eat</span>, <span class="title">Run</span> </span>&#123;</span><br><span class="line">    eat (food: <span class="built_in">string</span>): <span class="built_in">void</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    run (distance: <span class="built_in">number</span>): <span class="built_in">void</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>类：必须显示定义属性</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> name: <span class="built_in">string</span> = <span class="string">&#x27;init name&#x27;</span> <span class="comment">// 公有成员，默认</span></span><br><span class="line">    <span class="keyword">private</span> age: <span class="built_in">number</span> <span class="comment">// 私有成员，只能内部访问,子类成员不可以访问</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">readonly</span> gender: <span class="built_in">boolean</span> <span class="comment">// 受保护成员，外部不能访问，子类成员可以访问。只读属性，不可修改</span></span><br><span class="line"></span><br><span class="line">    <span class="title">constructor</span> (<span class="params">name: <span class="built_in">string</span>, age: <span class="built_in">number</span></span>) &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">        <span class="built_in">this</span>.age = age</span><br><span class="line">        <span class="built_in">this</span>.gender = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    sayHi (msg: <span class="built_in">string</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(msg)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> tom = <span class="keyword">new</span> Person(<span class="string">&#x27;tom&#x27;</span>, <span class="number">19</span>)</span><br><span class="line">tom.age <span class="comment">// 报错</span></span><br><span class="line">tom.gender <span class="comment">// 报错</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>抽象类：可以包含具体的实现，接口不包含。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 只能被继承不能new实例对象</span></span><br><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    eat (food: <span class="built_in">string</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;吃&#x27;</span> + food)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 抽象方法</span></span><br><span class="line">    <span class="keyword">abstract</span> run (distance: <span class="built_in">number</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    run(distance: <span class="built_in">number</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;run &#x27;</span> + distance)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> d = <span class="keyword">new</span> Dog()</span><br><span class="line">d.eat(<span class="string">&#x27;香肠&#x27;</span>)</span><br><span class="line">d.run(<span class="number">100</span>)</span><br></pre></td></tr></table></figure></li>
<li><p>泛型。定义函数，接口或者类的时候，没有指定具体的类型，使用时再指定具体类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将类型变成参数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createArray</span>&lt;<span class="title">T</span>&gt; (<span class="params">length: <span class="built_in">number</span>, value: T</span>):<span class="title">T</span>[] </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> arr = <span class="built_in">Array</span>&lt;T&gt;(length).fill(value)</span><br><span class="line">    <span class="keyword">return</span> arr</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> arr1 = createArray&lt;<span class="built_in">number</span>&gt;(<span class="number">3</span>, <span class="number">100</span>)</span><br><span class="line"><span class="keyword">const</span> arr2 = createArray&lt;<span class="built_in">string</span>&gt;(<span class="number">3</span>, <span class="string">&#x27;foo&#x27;</span>)</span><br></pre></td></tr></table></figure></li>
<li><p>类型声明</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">declare <span class="function"><span class="keyword">function</span> <span class="title">camelCase</span><span class="params">(input:<span class="keyword">string</span>)</span>:</span> <span class="keyword">string</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<hr>
<h2 id="JavaScript-性能优化"><a href="#JavaScript-性能优化" class="headerlink" title="JavaScript 性能优化"></a>JavaScript 性能优化</h2><h3 id="垃圾回收"><a href="#垃圾回收" class="headerlink" title="垃圾回收"></a>垃圾回收</h3><ol>
<li><p>js 中内存管理是自动的</p>
</li>
<li><p>对象不再被引用时是垃圾</p>
</li>
<li><p>对象不能从根上访问到时是垃圾</p>
<p><strong>可达对象：1.可以访问到的对象就是可达对象 2.可达标准是从根出发是否能被找到 3.js 中的根可以理解为全局变量对象</strong></p>
</li>
</ol>
<h3 id="GC-算法"><a href="#GC-算法" class="headerlink" title="GC 算法"></a>GC 算法</h3><ol>
<li><p>引用计数算法</p>
<ul>
<li>核心思想：设置引用数，判断当前引用数是否为 0</li>
<li>引用计数器</li>
<li>引用关系改变时修改引用数字</li>
<li>引用数字为 0 时立即回收</li>
</ul>
</li>
<li><p>引用计数算法优缺点</p>
<ul>
<li>发现垃圾时立即回收</li>
<li>最大限度减少程序暂停</li>
<li>无法回收循环引用的对象</li>
<li>时间开销大</li>
</ul>
</li>
<li><p>标记清除算法</p>
<ul>
<li>核心思想：分标记和清除两个阶段完成</li>
<li>遍历所有对象找标记活动对象（递归查找）</li>
<li>遍历所有对象清除没有标记的对象，同时把第一次遍历所做的标记抹掉</li>
<li>把回收的空间放到空闲列表上面，方便后续程序申请空间使用</li>
</ul>
</li>
<li><p>标记清除算法优缺点</p>
<ul>
<li>可以解决循环引用的对象</li>
<li>地址不连续，空间碎片化</li>
</ul>
</li>
<li><p>标记整理算法</p>
<ul>
<li>是标记清除的增强</li>
<li>标记阶段的操作和标记清除一致</li>
<li>清除阶段会先执行整理，移动对象位置</li>
</ul>
</li>
<li><p>V8 引擎</p>
<ul>
<li>即时编译</li>
<li>V8 内存设限 64 位 1.5G 32 位 800M</li>
</ul>
</li>
<li><p>V8 垃圾回收策略</p>
<ul>
<li>采用分代回收的思想</li>
<li>内存分为新生代、老生代</li>
<li>针对不同对象采用不同算法<ol>
<li>分代回收</li>
<li>空间复制</li>
<li>标记清除</li>
<li>标记整理</li>
<li>标记增量</li>
</ol>
</li>
</ul>
</li>
<li><p>V8 内存分配</p>
<ul>
<li>V8 内存空间一分为二</li>
<li>小空间用于存储新生代对象（64 位：32M | 32 位：16M）</li>
<li>新生代指的是存活时间较短的对象（局部作用域中的变量）</li>
</ul>
</li>
<li><p>新生代对象回收实现</p>
<ul>
<li>回收过程采用复制算法 + 整理标记</li>
<li>新生代内存区分为两个等大小空间</li>
<li>使用空间为 From，空闲空间为 To</li>
<li>所有对象存储于 From 空间（包括活动对象和非活动对象）</li>
<li>当 From 空间应用到一定程度后会触发 GC 机制，标记整理后将活动对象拷贝至 To</li>
<li>From 完成释放（From 和 To 交换空间）</li>
</ul>
<p>回收细节说明：</p>
<ol>
<li>拷贝过程中可能出现晋升</li>
<li>晋升就是讲新生代对象移动至老生代</li>
<li>一轮 GC 还存活的新生代需要晋升</li>
<li>To 空间的使用率超过 25%需要晋升至老生代</li>
</ol>
</li>
<li><p>老生代对象回收</p>
<ul>
<li>老生代对象存放在右侧老生代区域</li>
<li>64 位限制 1.4G，32 位限制 700M</li>
<li>老生代对象就是指存活时间较长的对象（全局变量，闭包）<br>实现过程：</li>
</ul>
<ol>
<li>主要采用标记清除、标记整理、增量标记算法</li>
<li>首先使用标记清除完成垃圾空间的回收</li>
<li>采用标记整理进行空间优化（当新生代晋升老生代时，同时也发现老生代空间不够存新生代晋升过来的，就会进行标记整理空间优化）</li>
<li>采用增量标记进行效率优化（将标记过程分段进行）</li>
</ol>
</li>
<li><p>内存问题的外在表现</p>
<ul>
<li>页面出现延迟加载或经常性暂停</li>
<li>页面持续性出现糟糕的性能（内存膨胀，分配的内存超过机器能力）</li>
<li>页面的性能随时间延长越来越差（内存泄漏）</li>
</ul>
</li>
<li><p>监控内存的几种方法<br>界定内存问题的标准</p>
<ul>
<li>内存泄漏：内存使用持续升高</li>
<li>内存膨胀：在多数设备上都存在性能问题</li>
<li>频繁垃圾回收：通过内存变化图进行分析</li>
</ul>
<p>监控方式：</p>
<ol>
<li>浏览器任务管理器</li>
<li>TImeline 时序图记录</li>
<li>堆块照查找分离 DOM（分离 DOM 存在是一种内存泄漏）</li>
<li>判断是否存在频繁的垃圾回收</li>
</ol>
</li>
<li><p>什么是分离 DOM</p>
<ul>
<li>界面元素存活在 DOM 树上</li>
<li>垃圾对象时的 DOM 节点</li>
<li>分离状态的 DOM 节点</li>
</ul>
</li>
</ol>
<h3 id="代码优化"><a href="#代码优化" class="headerlink" title="代码优化"></a>代码优化</h3><ol>
<li>慎用全局变量<ul>
<li>所有作用域链的顶端，所以会比较耗时，尽量放在局部作用域</li>
<li>不利于 GC 机制，耗内存</li>
<li>全局变量命名污染</li>
</ul>
</li>
<li>缓存全局变量</li>
<li>通过原型新增方法来替代构造函数中新增方法</li>
<li>避开闭包陷阱（容易内存泄漏）</li>
<li>避免属性访问方法使用</li>
<li>for 循环优化。将长度缓存</li>
<li>采用最优循环方式：简单遍历的话 foreach 优于 for 优于 for in</li>
<li>节点添加优化（回流和重绘）：createDocumentFragment() 文档碎片方法优于直接添加到 body</li>
<li>克隆优化节点操作：cloneNode(false)</li>
<li>直接量替换 Object 操作<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>] <span class="comment">// 性能好</span></span><br><span class="line"><span class="keyword">var</span> a1 = <span class="keyword">new</span> <span class="type">Array</span>(<span class="number">3</span>)</span><br><span class="line">a1[<span class="number">0</span>] = <span class="number">1</span></span><br><span class="line">a1[<span class="number">1</span>] = <span class="number">2</span></span><br><span class="line">a1[<span class="number">2</span>] = <span class="number">3</span></span><br></pre></td></tr></table></figure>
</li>
</ol>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/head1.png" alt=" 我啥都没有"/>
        <p>我啥都没有</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/head2.png" alt=" 就是有钱"/>
        <p>就是有钱</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/es6/" rel="tag"># es6</a>
          
            <a href="/tags/TypeScript/" rel="tag"># TypeScript</a>
          
            <a href="/tags/js/" rel="tag"># js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/life/life/me/" rel="next" title="me">
                <i class="fa fa-chevron-left"></i> me
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/notes/notes/functional-programming/" rel="prev" title="函数式编程与 JS 异步编程">
                函数式编程与 JS 异步编程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/favicon.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
                <a href="/archives">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ES-%E6%96%B0%E7%89%B9%E6%80%A7"><span class="nav-text">ES 新特性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ES2016"><span class="nav-text">ES2016</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ES2017"><span class="nav-text">ES2017</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#TypeScript-%E8%AF%AD%E8%A8%80"><span class="nav-text">TypeScript 语言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%9D%99%E6%80%81%E7%B1%BB%E5%9E%8B%E5%92%8C%E5%8A%A8%E6%80%81%E7%B1%BB%E5%9E%8B%EF%BC%88%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%9F%A5%E8%A7%92%E5%BA%A6%EF%BC%89"><span class="nav-text">静态类型和动态类型（类型检查角度）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Flow%EF%BC%8CJavaScript-%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%9F%A5%E5%99%A8%EF%BC%882014%EF%BC%8CFacebook%EF%BC%89"><span class="nav-text">Flow，JavaScript 类型检查器（2014，Facebook）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TypeScript"><span class="nav-text">TypeScript</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScript-%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96"><span class="nav-text">JavaScript 性能优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6"><span class="nav-text">垃圾回收</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GC-%E7%AE%97%E6%B3%95"><span class="nav-text">GC 算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96"><span class="nav-text">代码优化</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
 <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">二羊</span>

  
</div>

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
     <i class="fa fa-user"></i> 总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     <i class="fa fa-eye"></i>  总访客 <span id="busuanzi_value_site_uv"></span> 人
</span>
</div>





        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>

<!-- 页面点击小红心 -->

